/**
 * Created by tiansha on 2016/4/18.
 */

import React, {Component} from 'react';
import ReactDom from 'react-dom'

import axios from 'axios';

import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Thumbnail from 'react-bootstrap/lib/Thumbnail';

import 'component/style/imageUpload.styl';
import 'component/style/upload.css';

export default class ImageUpload extends Component {

  constructor(props) {
    super(props);
    this.state = {
      imagePreviewUrls: []
    };
    this._handleImageChange = this._handleImageChange.bind(this);
    this._handleSubmit = this._handleSubmit.bind(this);
  }

  _handleSubmit(e) {
    e.preventDefault();
    var options = [];
    let {imagePreviewUrls} = this.state;
    for (var i = 0; i < imagePreviewUrls.length; i++) {
      let optionName = "preview-option" + imagePreviewUrls[i].index;
      var optionValue = ReactDom.findDOMNode(this.refs[optionName]).value;
      options.push(optionValue);
    }

    var data = new FormData(); //document.getElementById("imageForm")
    imagePreviewUrls.forEach(fileInfo => {
      data.append(fileInfo.file.name, fileInfo.file, fileInfo.file.name);
    });
    data.append("options", options);

    var config = {
      progress: function(progressEvent) {
        var percentCompleted = progressEvent.loaded / progressEvent.total;
        console.log("progress " + percentCompleted);
      }
    };

    this.props.uploadImages(data);

    /*axios.put('/api/upload', data, config)
      .then(function (res) {
        console.log(res.data);
      })
      .catch(function (res) {
        console.log(res.data);
      });*/
  }

  _handleImageChange(e) {
    e.preventDefault();

    var loadImage = function(i, file) {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        reader.onloadend = () => {
          resolve({index: i, file: file, url: reader.result});
        }
        reader.readAsDataURL(file)
      });
    };

    var loadPromises = [];
    var files = [];
    //var files = e.target.files;
    for (var i = 0; i < e.target.files.length; i++) {
      loadPromises.push(loadImage(i, e.target.files[i]));
      files.push(e.target.files[i]);
    }
    console.log(loadPromises.length);
    //var loadPromises = e.target.files.map(file => loadImage(file));
    Promise.all(loadPromises).then(imagePreviewUrls => {
      this.setState({
        imagePreviewUrls: imagePreviewUrls
      });
    })

  }

  render() {
    let {imagePreviewUrls} = this.state;
    let $imagePreview = null;
    if (imagePreviewUrls) {
      $imagePreview = imagePreviewUrls.map(urlInfo => {
        let optionName = "preview-option" + urlInfo.index;
        return (<Col xs={6} md={4}>
          <Thumbnail src={urlInfo.url} className="card-img-top img-responsive" />
          <div className="card-block">
            Type: <select ref={optionName}>
              <option value="a">a</option>
              <option value="b">b</option>
            </select>
          </div>
        </Col>);
      });
    } else {
      $imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
    }

    return (
      <Grid>
      <div className="previewComponent">
        <form onSubmit={(e)=>this._handleSubmit(e)}>
          <input className="fileInput" type="file" onChange={(e)=>this._handleImageChange(e)} multiple/>
          <Grid>
            <Row>
              {$imagePreview}
            </Row>
          </Grid>
          <button className="submitButton" type="submit" onClick={(e)=>this._handleSubmit(e)}>Upload Image</button>
        </form>
      </div>
      </Grid>
    )
  }


}
